/* 
 *    
 *    dodol android screenshot capture and share library v1.0 (1. 30. 2011)
 *    
 *    homepage:
 *     http://dodol.kr
 *    source:
 *     http://code.google.com/p/dodol-android-screenshot-capture/
 *     
 *    Copyright (C) 2011  dodol [dodol.kr@gmail.com]
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

package lib.dodol.screenshot;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class DodolScreenshot {

	private Activity mActivity;
	private Bitmap mImageBitmap;
	private String mAppId;
	private String mMessage;
	private String mResultMessage;

	// constructor
	
	public DodolScreenshot(Activity activity) {
		this.mActivity = activity;
	}
	
	// public method
	
	public Bitmap setCaptureSource(View view) {
		mImageBitmap = makeBitmapImage(view);
		return mImageBitmap;
	}
	
	public Bitmap setCaptureSource(Bitmap bitmap) {
		mImageBitmap = bitmap;
		return mImageBitmap;
	}

	public void setAppId(String mAppId) {
		this.mAppId = mAppId; 
		
	}

	public void setUserMessage(String msg) {
		this.mMessage = msg;
	}
	
	public String getUserMessage() {
		// TODO Auto-generated method stub
		return mMessage;
	}

	public String upload() {
		if(mImageBitmap == null) {
			Log.e("dodol-screenshot", "screenshot source has not been set");
			return "no screenshot source";
		}
		mResultMessage = processUploadRequest(); 
		return mResultMessage;
	}
	
	public boolean isSuccess() {
		return mResultMessage != null && mResultMessage.contains("http");
	}
	
	public String getUrl() {
		return isSuccess() ? mResultMessage : null; 
	}
	
	public Intent getSendIntent(String userMessage) {
		if(isSuccess()) {
			Intent intent = new Intent(Intent.ACTION_SEND);
			// "Screenshot: " is 12 character 
			// url length is less than 50 character
			intent.putExtra(Intent.EXTRA_TEXT, userMessage + "Screenshot: " + mResultMessage);
			intent.setType("text/plain");
			return intent;
		} else {
			return null;
		}
	}
	
	// private methods
	
	private Bitmap makeBitmapImage(View mMainLayout) { 
		Bitmap bitmap;
		
		try {
			bitmap = Bitmap.createBitmap(mMainLayout.getWidth(), mMainLayout.getHeight(), Config.ARGB_8888);
			Canvas canvas = new Canvas();
			canvas.setBitmap(bitmap);
			mMainLayout.draw(canvas);
		} catch (Exception e) {
			Log.e("dodol-screenshot", "not enough memory");
			Toast.makeText(mActivity, "dodol-screenshot: not enough memory", Toast.LENGTH_LONG).show();
			return null;
		}
		return bitmap;
	}
	
	private String processUploadRequest() {
		
		HttpURLConnection conn = null;
		DataOutputStream dos = null;

	   	try {

	   		String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary = "*****";

            String urlString = "http://dodol-screenshot.appspot.com/post";
            URL url = new URL(urlString);
            conn = (HttpURLConnection) url.openConnection();

            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            
            conn.setRequestMethod("POST");
           
            conn.setRequestProperty("Charset", "utf-8");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

            dos = new DataOutputStream( conn.getOutputStream() );

            // additional field and data
			ArrayList<String> data = new ArrayList<String>();
			data.add("package");
			data.add(mActivity.getPackageName());

			data.add("appid");
			data.add(mAppId);
			
			data.add("title");
			data.add(mMessage);
			
			data.add("language");
			data.add(mActivity.getResources().getConfiguration().locale.getISO3Language());
			
			for(int i = 0; i < data.size(); i += 2) {
				dos.writeBytes(twoHyphens + boundary + lineEnd);
				dos.writeBytes("Content-Disposition: form-data; name=\"" + data.get(i)+ "\"" + "\r\n" + lineEnd);
				dos.write(data.get(i + 1).getBytes("utf-8"));
				dos.writeBytes(lineEnd);
			}
           dos.writeBytes(twoHyphens + boundary + lineEnd);
           
           // upload image file 
           dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"screenshot\"" + lineEnd);
           dos.writeBytes(lineEnd);
           
           ByteArrayOutputStream  byteArray = new ByteArrayOutputStream();
           mImageBitmap.compress(CompressFormat.JPEG, 90, byteArray);
           
           byte[] byteImageData = byteArray.toByteArray();
           dos.write(byteImageData, 0, byteImageData.length);

           dos.writeBytes(lineEnd);
           dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

           dos.flush();
           dos.close();

           // receive result from server
           InputStream is = conn.getInputStream();  

           BufferedReader reader = new BufferedReader(new InputStreamReader(is));
           urlString = reader.readLine();
			
           conn.disconnect();
           return urlString;
           
	   	} catch (Exception e) {
	    	e.printStackTrace();
	    	Log.e("dodol-screenshot", "Sorry, screenshot upload failed. See logcat exception message");
	    	Toast.makeText(mActivity, "Sorry, screenshot upload failed.", Toast.LENGTH_LONG).show();
	   	}
		return null;
    }

}